<template>
  <a-modal
    :title="title"
    :width="630"
    :visible="visible"
    centered
    :maskClosable="false"
    @ok="handleOk"
    :okText="$t('确定')"
    @cancel="handleCancel"
    :cancelText="$t('取消')"
    v-drag
  >
    <a-form>
      <a-form-item :label="$t('本次已选商品')" :labelCol="{ span: 7 }" :wrapperCol="{ span: 15 }">
        {{ goodsIdList.length }} {{ $t('种') }}
      </a-form-item>
      <a-form-item :label="$t('每种商品打印张数')" :labelCol="{ span: 7 }" :wrapperCol="{ span: 15 }">
        <a-input-number v-model="number" :placeholder="$t('请输入打印张数')" :min="0" style="width: 100%" />
      </a-form-item>
    </a-form>
    <div style="height: 30px">
      <label style="color: red; display: inline-block; margin-left: 30px" v-text="notifyInfo"></label>
    </div>
  </a-modal>
</template>
<script>
import { isEmpty } from '@/api/manage'
import { getAction } from '@api/manage'
export default {
  name: 'batchPrint',
  props: [],
  data() {
    return {
      title: this.$t('批量打印'),
      visible: false,
      notifyInfo: '',
      number: null,
      goodsIdList: [],
      printList: [],
      picture: '',
    }
  },
  created() {
    getAction('/shop/bisShop/list').then((res) => {
      if (res.success) {
        this.picture = res.result.records[0].shopPicture
      }
    })
  },
  methods: {
    keydown() {
      let that = this
      if (event != null) {
        if (event.keyCode == 13) {
          var element = event.srcElement || event.target
          if (document.all) {
            event.keyCode = 9
          } else {
            event.preventDefault()
            that.handleOk()
          }
          event.keyCode = 0
          return
        }
      }
    },
    edit(datas) {
      let that = this
      that.visible = true
      that.goodsIdList = datas
      that.notifyInfo = ''
      that.number = null
    },
    close() {
      this.visible = false
    },
    async handleOk() {
      let that = this,
        imgCont = '',
        printLogo = 0
      printLogo = plugin.getData(
        'C:\\ProgramData\\leyudm\\Manage\\data.json',
        'printLogo',
        localStorage.getItem('printLogo')
      )
      if (printLogo == 1 && that.picture) {
        imgCont = await that.convertImageToBase64(that.picture)
      }
      let result = plugin.getData(
        'C:\\ProgramData\\leyudm\\Manage\\data.json',
        'printName',
        localStorage.getItem('printName')
      )
      if (isEmpty(result)) {
        that.errorMessage(that.$t('请先设置打印机'))
        return
      }
      if (that.number == null || that.number === '') {
        that.errorMessage(that.$t('请输入打印张数'))
        return
      }
      let param = {
        ids: that.goodsIdList.length == 1 ? that.goodsIdList[0] : that.goodsIdList,
        isQs: true,
      }
      getAction('/goods/bisGoodsInfor/queryByIds', param).then((res) => {
        if (res.success) {
          let arr = res.result.find((item) => {
            return !(item.barCode && item.barCode != '' && item.barCode != null && item.barCode != undefined)
          })
          if (arr) {
            that.errorMessage('【' + arr.name + '】' + that.$t('没有条形码'))
            return
          }
          let fontSize = Number(plugin.getData('C:\\ProgramData\\leyudm\\Manage\\data.json', 'printFontSize', 9))
          res.result.forEach((item) => {
            if (that.number === '') {
              that.number = 1
            }
            for (let i = 0; i < that.number; i++) {
              let GoodsName = []
              let reg = new RegExp('[^\x00-\xff]', 'ig')
              let rowLen = 0
              let rowNum = 0
              if (that.getByteLen(item.name) > 16) {
                for (let j = 0; j < item.name.length; j++) {
                  if (item.name.charAt(j).match(reg) != null) {
                    if (rowLen === 15) {
                      rowLen = 0
                      rowNum++
                      j--
                      continue
                    }
                    rowLen += 2
                  } else {
                    rowLen += 1
                  }
                  if (GoodsName[rowNum] === undefined) {
                    GoodsName[rowNum] = ''
                  }
                  GoodsName[rowNum] += item.name.charAt(j)
                  if (rowLen === 16) {
                    rowLen = 0
                    rowNum++
                  }
                }
              } else {
                GoodsName[0] = item.name
              }
              let exArr = []
              let exValue = ''
              if (item.allowSale == 'Y') {
                if (item.price != 0) {
                  exArr.push(item.price + this.$t('￥'))
                }
                exValue += that.$t('售价') + ':' + item.price + ' '
              }
              if (item.allowCoin == 'Y') {
                if (item.coin != 0) {
                  exArr.push(item.coin + that.$t('币'))
                }
                exValue += that.$t('币') + ':' + item.coin + ' '
              }
              if (item.allowLottery == 'Y') {
                if (item.lottery != 0) {
                  exArr.push(item.lottery + that.$t('票'))
                }
                exValue += that.$t('票') + ':' + item.lottery + ' '
              }
              if (item.allowPoints == 'Y') {
                if (item.points != 0) {
                  exArr.push(item.points + that.$t('A币'))
                }
                exValue += that.$t('A币') + ':' + item.points + ' '
              }
              if (item.allowIntegral == 'Y') {
                if (item.integral != 0) {
                  exArr.push(item.integral + that.$t('积分'))
                }
                exValue += that.$t('积分') + ':' + item.integral + ' '
              }
              if (item.allowAlottery == 'Y') {
                if (item.alottery != 0) {
                  exArr.push(item.alottery + that.$t('A票'))
                }
                exValue += that.$t('A票') + ':' + item.alottery + ' '
              }

              let printElementList = []
              if (typeof getPrintList != 'undefined') {
                if (rowNum > 0) {
                  printElementList.push({
                    text: '\xa0' + GoodsName[1],
                    fontSize: 6,
                    weight: 700,
                    fontName: '宋体',
                    left: 0,
                    top: 10 + Math.min(1, rowNum) * 30,
                  })
                }
                printElementList.push({
                  text: '\xa0' + GoodsName[0],
                  fontSize: 6,
                  weight: 700,
                  fontName: '宋体',
                  left: 0,
                  top: 10,
                  barCode: {
                    code: item.barCode,
                    left: 0,
                    top: 10 + 15 + Math.min(1, rowNum) * 15,
                    width: 140,
                    height: 50,
                  },
                })
                if (exValue.length > 15) {
                  printElementList.push({
                    text: exValue.slice(0, 15),
                    fontSize: fontSize,
                    weight: 400,
                    fontName: '宋体',
                    left: 0,
                    top: 30 + Math.min(1, rowNum) * 20 + 120,
                  })
                  printElementList.push({
                    text: exValue.slice(15),
                    fontSize: fontSize,
                    weight: 400,
                    fontName: '宋体',
                    left: 0,
                    top: 25 + 30 + Math.min(1, rowNum) * 20 + 120,
                  })
                } else {
                  printElementList.push({
                    text: exValue,
                    fontSize: fontSize,
                    weight: 400,
                    fontName: '宋体',
                    left: 0,
                    top: 30 + Math.min(1, rowNum) * 30 + 120,
                  })
                }
                plugin.print(result, printElementList)
              } else {
                let fontwidth = 8 * 2
                if (printLogo == 1 && that.picture) {
                  printElementList.push({
                    text: imgCont,
                    type: 'base64',
                    left: 160,
                    top: 10,
                    width: 50,
                    height: 50,
                  })
                }
                let str = '',
                  exheight = 0

                if (printLogo == 1) {
                  if (rowNum > 0) {
                    printElementList.push({
                      text: '\xa0' + GoodsName[1],
                      fontSize: 8,
                      weight: 700,
                      fontName: '宋体',
                      left: 60,
                      top: 10 + Math.min(1, rowNum) * fontwidth,
                    })
                  }
                  printElementList.push({
                    text: '\xa0' + GoodsName[0],
                    fontSize: 8,
                    weight: 700,
                    fontName: '宋体',
                    left: 60,
                    top: 10,
                  })
                  if (exArr.length > 4) {
                    exheight = fontwidth * 2
                    str =
                      '\xa0' +
                      exArr.slice(0, 2).join('/') +
                      '\n' +
                      '\xa0' +
                      exArr.slice(2, 4).join('/') +
                      '\n' +
                      '\xa0' +
                      exArr.slice(4, exArr.length).join('/')
                  }
                  if (exArr.length <= 4 && exArr.length > 2) {
                    exheight = fontwidth * 2
                    str =
                      '\xa0' +
                      exArr.slice(0, 2).join('/') +
                      '\n' +
                      '\xa0' +
                      exArr.slice(2, Math.min(4, exArr.length)).join('/')
                  }
                  if (exArr.length <= 2) {
                    exheight = fontwidth
                    str = '\xa0' + exArr.join('/')
                  }
                  console.log(str)
                  printElementList.push({
                    text: str,
                    fontSize: 10,
                    weight: 400,
                    fontName: '宋体',
                    left: 60,
                    top: 10 + (Math.min(1, rowNum) + 1) * fontwidth,
                    fontStyle: 1
                  })
                  printElementList.push({
                    text: '',
                    barCode: {
                      code: item.barCode,
                      left: 60,
                      top: 8 + Math.max((Math.min(1, rowNum) + 1) * fontwidth + exheight, 65),
                      width: 150,
                      height: 35,
                    },
                  })
                } else {
                  if (rowNum > 0) {
                    printElementList.push({
                      text: '\xa0' + GoodsName[1],
                      fontSize: fontSize,
                      weight: 700,
                      fontName: '宋体',
                      left: 60,
                      top: 10 + Math.min(1, rowNum) * fontwidth,
                    })
                  }
                  printElementList.push({
                    text: '\xa0' + GoodsName[0],
                    fontSize: fontSize,
                    weight: 700,
                    fontName: '宋体',
                    left: 60,
                    top: 10,
                  })
                  if (exArr.length > 3) {
                    exheight = fontwidth * 2
                    str =
                      '\xa0' +
                      exArr.slice(0, 3).join('/') +
                      '\n' +
                      '\xa0' +
                      exArr.slice(3, exArr.length).join('/')
                  }
                  if (exArr.length <= 3) {
                    exheight = fontwidth
                    str = '\xa0' + exArr.join('/')
                  }
                  printElementList.push({
                    text: str,
                    fontSize: fontSize+2,
                    weight: 400,
                    fontName: '宋体',
                    left: 60,
                    top: 10 + (Math.min(1, rowNum) + 1) * fontwidth,
                    fontStyle: 1
                  })
                  printElementList.push({
                    text: '',
                    barCode: {
                      code: item.barCode,
                      left: 60,
                      top: 8 + Math.max((Math.min(1, rowNum) + 1) * fontwidth + exheight, 65),
                      width: 150,
                      height: 35,
                    },
                  })
                }
                plugin.print(result, printElementList)
              }
            }
            that.$message.success(that.$t('打印成功'))
            that.close()
          })
        } else {
          that.errorMessage(res.message)
        }
      })
    },
    handleCancel() {
      let that = this
      that.close()
    },
    errorMessage(message) {
      let that = this
      that.notifyInfo = message
    },
    emptyStr(length) {
      let str = ''
      for (let i = 0; i < length; i++) {
        str += '\xa0'
      }
      return str
    },
    getByteLen(val) {
      let len = 0
      for (let i = 0; i < val.length; i++) {
        if (val[i].match(/[^\x00-\xff]/gi) != null) {
          len += 2
        } else {
          len += 1
        }
      }
      return Math.floor(len)
    },
    /*   convertImageToBase64(url) {
      return new Promise((resolve, reject) => {
        // 创建一个XMLHttpRequest对象
        const xhr = new XMLHttpRequest()
        // 当请求完成时触发load事件
        xhr.onload = function () {
          if (xhr.status === 200) {
            // 创建一个图片对象
            const img = new Image()
            img.setAttribute("crossOrigin","Anonymous")
            // 当图片加载完成时触发load事件
            img.onload = function () {
              // 创建一个Canvas元素
              const canvas = document.createElement('canvas')
              const ctx = canvas.getContext('2d')
              // 设置Canvas的宽高和图片尺寸一致
              canvas.width = img.width
              canvas.height = img.height
              // 在Canvas上绘制图片
              ctx.drawImage(img, 0, 0, img.width, img.height)
              // 将Canvas转换为Base64格式的字符串
              const dataURL = canvas.toDataURL('image/png')
              // 返回Base64字符串
              resolve(dataURL)
            }
            // 设置图片源
            img.src = URL.createObjectURL(xhr.response)
          } else {
            reject(new Error(xhr.statusText)) // 处理请求错误
          }
        }
        // 发起GET请求
        xhr.open('GET', url+'?s='+Math.random().toString(), true)
        xhr.responseType = 'blob'
        xhr.setRequestHeader("Cache-Control","no-cache")
        xhr.send()
      })
    },
    convertImageToBase64(src) {
      return new Promise((resolve) => {
        const img = new Image()
        img.setAttribute("crossOrigin","Anonymous")
        img.src = src
        img.onload = function () {
          const canvas = document.createElement('canvas')
          canvas.width = img.width
          canvas.height = img.height
          const ctx = canvas.getContext('2d')
          ctx.drawImage(img, 0, 0, img.width, img.height)
          const ext = img.src.substring(img.src.lastIndexOf('.') + 1).toLowerCase()
          const dataURL = canvas.toDataURL('image/' + ext)
          resolve(dataURL)
        }
      })
    }, */
    convertImageToBase64(src) {
      return new Promise((resolve) => {
        getAction('/res/imageToBase64', { imagePath: src }).then((res) => {
          let str = ''
          if (res.success) {
            str = 'data:image/jpg;base64,' + res.result
          }
          resolve(str)
        })
      })
    },
  },
}
</script>

<style lang="less">
.cus-input-password.ant-input-password .ant-input {
  height: 50px;
  font-size: 18px;
}
</style>
